// 启动一个静态服务器
var gulp = require('gulp');
var browserSync = require('browser-sync');
var opn = require('opn');
var less = require('gulp-less');
var clean = require('gulp-clean');
// 接口跨域代理配置
var proxy = require('http-proxy-middleware');
// 服务器实例
var bs = browserSync.create();

var proxyMiddleware = proxy('/api', {
  // target: 'http://api.dianzhantech.com/mock/5a291db82c00e23a42afe1c0',
  target: 'http://dztest.rzbtech.com',
  changeOrigin: true
});

// 每次构建的时候需要将以前的构建目录以及文件先删除
gulp.task('clean', function() {
  return gulp.src('dist/', { read: false })
    .pipe(clean({force: true}));
});
// 实时刷新
function reloadHandler() {
  bs.reload();
};
// 复制文件
function copyImgHandler () {
  return gulp.src('./src/img/**/*.png')
    .pipe(gulp.dest('./dist/img/'))
    .on('end', reloadHandler);
};

// 复制图片
gulp.task('copyImg', copyImgHandler);

// 编译Less
gulp.task('complierLess', function () {
  gulp.src('./src/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('./dist/css'))
    .on('end', reloadHandler);
});

// 拷贝Html
gulp.task('copyHtml', function() {
  return gulp.src('./src/html/*.html')
    .pipe(gulp.dest('./dist/'))
    .on('end', reloadHandler);
});

// 拷贝Html
gulp.task('copyjs', function() {
  return gulp.src('./src/js/*.js')
    .pipe(gulp.dest('./dist/js'))
    .on('end', reloadHandler);
});

gulp.task('default', ['clean'], function() {
  gulp.start(['copyImg', 'complierLess', 'copyHtml', 'copyjs'], function() {
    bs.init({
      server: {
        baseDir: './dist/',
        middleware: [ proxyMiddleware ]
      },
      port: 8080,
      open: false
    }, function() {
      var homepage = 'http://localhost:8080/useGuide.html';
      opn(homepage);
    });
  });
  gulp.watch('./src/less/*.less', ['complierLess']);
  gulp.watch('./src/html/*.html', ['copyHtml']);
});
